package com.demo32_求最长有效括号;

import java.util.Stack;

public class Solution {
    public static void main(String[] args) {
        String s="()(())";
        int i = longestValidParentheses(s);
        System.out.println(i);
    }
    public static int longestValidParentheses(String s) {
        Stack<Character> stack = new Stack<>();
        int count =0;
        int max=0;
        boolean flag=false;// 是否连续
        for (int i = 0; i < s.length(); i++) {
            if (stack.isEmpty()){
                stack.push(s.charAt(i));
            }else {
                char peek = stack.peek();
                if (peek=='('){
                    if (peek ==(s.charAt(i)==')' ?'(':')') ){
                        flag=true;
                        stack.pop();
                        count+=2;
                    }else {
                        flag=false;
                        stack.push(s.charAt(i));
                    }
                }else {
                    // 上一次是连续的成功 弹出 , 说明这次是放左括号,可以为true

                    stack.push(s.charAt(i));
                }
            }


            if (flag==false||i==s.length()-1){
                max=max==0?count:Math.max(count,max);
                count=0;
            }
        }
        return max;
    }
}
